package com.itany.corejava.code13_jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author Miss Chen
 * @version 1.0
 * @date 2024年08月08日13:52
 */
public class Test11_批处理 {
    public static void main(String[] args) throws DataAccessException {
        test01();
        test02();
    }
    public static void test01() throws DataAccessException {
        Connection conn=null;
        PreparedStatement ps=null;
        try {
            conn=JDBCUtil.getConnection();

            String sql=new StringBuffer()
                    .append(" insert into ")
                    .append(" t_user ")
                    .append(" (username,password,phone,address) ")
                    .append(" values ")
                    .append(" (?,?,?,?) ")
                    .toString();
           long begin=System.currentTimeMillis();
            ps=conn.prepareStatement(sql);
           for(int i=0;i<100;i++){

               ps.setString(1,"aa");
               ps.setString(2,"123");
               ps.setString(3,"12345678987");
               ps.setString(4,"nanjing");
               ps.executeUpdate();
           }
           long end=System.currentTimeMillis();

            System.out.println("1添加100条数据共消耗了"+(end-begin)+"毫秒");
        } catch (DataAccessException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtil.close(conn,ps,null);
        }
    }

    public static void test02() throws DataAccessException {
        Connection conn=null;
        PreparedStatement ps=null;
        try {
            conn=JDBCUtil.getConnection();

            String sql=new StringBuffer()
                    .append(" insert into ")
                    .append(" t_user ")
                    .append(" (username,password,phone,address) ")
                    .append(" values ")
                    .append(" (?,?,?,?) ")
                    .toString();
            long begin=System.currentTimeMillis();
            ps=conn.prepareStatement(sql);
            for(int i=0;i<100;i++){

                ps.setString(1,"aa");
                ps.setString(2,"123");
                ps.setString(3,"12345678987");
                ps.setString(4,"nanjing");
                //将ps对象添加到缓冲区
                ps.addBatch();
            }
            //批量执行
            ps.executeBatch();
            long end=System.currentTimeMillis();

            System.out.println("2添加100条数据共消耗了"+(end-begin)+"毫秒");
        } catch (DataAccessException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtil.close(conn,ps,null);
        }
    }

}
